#include <STC15F2K60S2.H>
#include "iic.h"

sbit key_lie_1 = P4^4;
sbit key_lie_2 = P4^2;
sbit key_lie_3 = P3^5;
sbit key_lie_4 = P3^4;

unsigned char code nixienumber[] = { 0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0xFF};
unsigned char code k_n[4][4] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
unsigned char keycount = 0,key_re = 0,key_value = 0;

void Timer2Init(void)		//500微秒@12.000MHz
{
	AUXR |= 0x04;		//定时器时钟1T模式
	T2L = 0x90;		//设置定时初值
	T2H = 0xE8;		//设置定时初值
	EA = 1;
	IE2 |= 0x04;
	AUXR |= 0x10;		//定时器2开始计时
}


void Latch(unsigned char p2,unsigned char p0)
{
	P2 = (P2 & 0x1f | p2);
	P0 = p0;
	P2 &= 0x1f;
}

void Delay500us()		//@12.000MHz
{
	unsigned char i, j;

	i = 6;
	j = 211;
	do
	{
		while (--j);
	} while (--i);
}


void nixie(unsigned char location,unsigned char number)
{
	Latch(0xe0,0xff);
	Latch(0xc0,0x01<<(location - 1));
	Latch(0xe0,nixienumber[number]);
	Delay500us();
}

void Delay(unsigned char c)		//@12.000MHz
{
	while(c--)
	{
	unsigned char i, j;

	i = 12;
	j = 169;
	do
	{
		while (--j);
	} while (--i);
}
}


unsigned char Key(void)
{
	static unsigned char k_i = 0;
	P3 |= 0x3f;
	P3 &= ~(0x01<<k_i);
	if(key_lie_1 == 0){Delay(5);while(key_lie_1 == 0);return k_n[k_i][0];}
	if(key_lie_2 == 0){Delay(5);while(key_lie_1 == 0);return k_n[k_i][1];}
	if(key_lie_3 == 0){Delay(5);while(key_lie_1 == 0);return k_n[k_i][2];}
	if(key_lie_4 == 0){Delay(5);while(key_lie_1 == 0);return k_n[k_i][3];}
	k_i++;
	if(k_i == 4)
		k_i = 0;
	return 0;
}

//ad光敏0x41，滑动0x43
unsigned int ad_read(unsigned int addr)
{
	unsigned int ad;
	IIC_Start();
	IIC_SendByte(0x90);
	IIC_WaitAck();
	IIC_SendByte(addr);
	IIC_WaitAck();
	
	IIC_Start();
	IIC_SendByte(0x91);
	IIC_WaitAck();
	
	ad = IIC_RecByte();
	IIC_SendAck(1);
	IIC_Stop();
	return ad;
}

//da

void da_wirte(unsigned int dat)
{
	IIC_Start();
	IIC_SendByte(0x90);
	IIC_WaitAck();
	
	IIC_SendByte(0x41);
	IIC_WaitAck();
	
	IIC_SendByte(dat);
	IIC_WaitAck();
	IIC_Stop();
}
